package bold.module.netty;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.log4j.Log4j2;

import java.nio.charset.StandardCharsets;

@ChannelHandler.Sharable
@Log4j2
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        buf.resetReaderIndex();
        buf.release();
        String body = new String(data, StandardCharsets.UTF_8);
        log.info("收到客户端消息 :[{}]",body);
        if("exit".equals(body)){
            ctx.close();
            return;
        }
        ByteBuf resp = Unpooled.copiedBuffer(("服务端-收到"+body).getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(resp);//代替write+flush 不会内存泄漏
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause);
        ctx.close();
    }
}
